/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val,Node _left,Node _right) {
        val = _val;
        left = _left;
        right = _right;
    }
};
*/
class Solution {
    Node head = null;
    Queue<Node> queue = new LinkedList<>();
    Node pre = null;
    public Node treeToDoublyList(Node root) {
        if(null == root) {
            return null;
        }
        inorder(root);
        head.left = pre;
        pre.right = head;
        return head;
    }
    public void inorder(Node root) {
        if(null == root) {
            return;
        }
        inorder(root.left);
        if(null == pre) {
            head = root;
        }else {
            pre.right = root;
        }
        root.left = pre;
        pre = root;
        inorder(root.right);
    }
    public Node treeToDoublyList1(Node root) {
        if(null == root) {
            return null;
        }
        inorder(root);
        
        head = queue.peek();
        Node cur = queue.poll();
        while(!queue.isEmpty()) {
            cur.right = queue.poll();
            cur.right.left = cur;
            cur = cur.right;
        }
        head.left = cur;
        cur.right = head;
        return head;
    }
    //把中序遍历结果放到队列里
    public void inorder1(Node root) {
        if(null == root) {
            return;
        }
        inorder(root.left);
        queue.offer(root);
        inorder(root.right);
    }
}